#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "Config.h"
#include "StunImpediments.h"
#include "FileOperation.h"


#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //Android
#include <jni.h>
#include "platform\android\jni\JniHelper.h"
#include <android/log.h>
#endif

USING_NS_CC;

using namespace cocos2d;

using namespace std;

using namespace CocosDenshion;

int nTimeDie, nTimeDisAppear;

CCScene* HelloWorld::scene()
{
	// 'scene' is an autorelease object
	CCScene *scene = CCScene::create();

	// 'layer' is an autorelease object
	HelloWorld *layer = HelloWorld::create();

	// add layer as a child to scene
	scene->addChild(layer);

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
	//	SHARED_SPRITE_CACHE;	
	mSize = CCDirector::sharedDirector()->getWinSize();

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	/////////////////////////////
	// 2. add a menu item with "X" image, which is clicked to quit the program
	//    you may modify it.

	// add a "close" icon to exit the progress. it's an autorelease object
	//   CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
	//                                       "CloseNormal.png",
	//                                       "CloseSelected.png",
	//                                       this,
	//                                       menu_selector(HelloWorld::menuCloseCallback));
	//   
	//pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
	//                               origin.y + pCloseItem->getContentSize().height/2));

	//   // create menu, it's an autorelease object
	//   CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
	//   pMenu->setPosition(CCPointZero);
	//   this->addChild(pMenu, 1);

	/////////////////////////////
	// 3. add your codes below...

	// add a label shows "Hello World"
	// create and initialize a label

	//CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
	//
	//// position the label on the center of the screen
	//pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
	//                        origin.y + visibleSize.height - pLabel->getContentSize().height));

	//// add the label as a child to this layer
	//this->addChild(pLabel, 1);

	//// add "HelloWorld" splash screen"
	//CCSprite* pSprite = CCSprite::create("HelloWorld.png");

	//// position the sprite on the center of the screen
	//pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

	//// add the sprite as a child to this layer
	//this->addChild(pSprite, 0);
	
	enableMusic = true;

	if (enableMusic){
		SimpleAudioEngine::sharedEngine()->setEffectsVolume(1);
	}
	else{
		SimpleAudioEngine::sharedEngine()->setEffectsVolume(0);
	}



	//fCreatePanelGameOver(this);
	countGameOver = 0;
	fResetGame(this);

	scheduleUpdate();

	return true;
}

void HelloWorld::musicController(CCObject* pSender){
	if (enableMusic){
		SimpleAudioEngine::sharedEngine()->setEffectsVolume(0);
	}
	else{
		SimpleAudioEngine::sharedEngine()->setEffectsVolume(1);
	}

	enableMusic = !enableMusic;
}


// 1/60
void HelloWorld::update(float delta)
{
	fBaseScreen();
	if(mIsDie == 1)
	{

		nTimeDie--;

		if(nTimeDie == 0)
		{
			fCreatePanelGameOver(this);
		}
	}
}

void HelloWorld::fResetGame(CCObject* pSender)
{
	this->removeAllChildrenWithCleanup(true);

	CCMenu *menu = CCMenu::create();
	CCMenuItem* enableSound = NULL, *disableSound = NULL;
	enableSound = CCMenuItemImage::create("icon_music.png", "icon_music_disable.png");
	disableSound = CCMenuItemImage::create("icon_music_disable.png", "icon_music.png");

	enableSound->setScale(0.4);
	disableSound->setScale(0.4);
	if (enableMusic){
		SimpleAudioEngine::sharedEngine()->setEffectsVolume(1);
		CCMenuItemToggle* speaker = CCMenuItemToggle::createWithTarget(this, menu_selector(HelloWorld::musicController), enableSound, disableSound, NULL);

		speaker->setPosition(ccp(speaker->getContentSize().width / 2, speaker->getContentSize().height / 4 - 12));
		// add to menu
		menu->addChild(speaker, kZorderLabelScore);
	}
	else{
		SimpleAudioEngine::sharedEngine()->setEffectsVolume(0);

		CCMenuItemToggle* speaker = CCMenuItemToggle::createWithTarget(this, menu_selector(HelloWorld::musicController), disableSound, enableSound, NULL);
		//speaker->setAnchorPoint(ccp(0.5, 0.5));
		speaker->setPosition(ccp(speaker->getContentSize().width / 2, speaker->getContentSize().height / 4 - 12));
		// add to menu
		menu->addChild(speaker, kZorderLabelScore);
	}
	menu->setPosition(ccp(0, mSize.height * 0.95));
	menu->setAnchorPoint(ccp(0.5, 0.5));
	this->addChild(menu, kZorderLabelScore - 1);

	SimpleAudioEngine::sharedEngine()->stopAllEffects();

	fInitValue();

	fAddBackgroundTable();

	fAddLabelScore();

	fCreateUIImageLife();

	fAddListImpediments();//them vat can

	fCreateOverlay(this);

	hideAdsAdmob();
}

void HelloWorld::fInitValue()
{
	isGameOver = 0;

	mIsDie = 0;

	score = 0;

	countdown = kCountdown;

	life = kLife;

	mCockRoachDie = 0;

	listCockRoach = CCArray::createWithCapacity(kNumCockRoachMax);

	listCockRoach->retain();
}

void HelloWorld::fCreateOverlay(CCLayer* parent)
{    
	// create layer overlay with white color and opacity = 80
	CCLayerColor* overlay = CCLayerColor::create( ccc4(255, 255, 255, 80) );

	SimpleAudioEngine::sharedEngine()->playEffect(kMusicFirst);

	CCString* strp = CCString::createWithFormat("%d", countdown);

	// create label with value init
	CCLabelTTF* lbCountDown = CCLabelTTF::create(strp->getCString(), kFontName, kFontSize * 2);

	// set position of label on layer overlay
	lbCountDown->setPosition(ccp(mSize.width/2, mSize.height/2));

	// add label into layer overlay
	overlay->addChild(lbCountDown, kZorderOverlayLabel, kTagOverlayLabel);

	// add layer overlay into parent
	parent->addChild(overlay, kZorderOverlay, kTagOverlay);

	// set up schedule count down
	schedule(schedule_selector(HelloWorld::fRemoveOverlay), 0.5f);
}

void HelloWorld::fRemoveOverlay(float delta)
{
	// get layer overlay by tag
	CCLayerColor* layer = (CCLayerColor*)getChildByTag(kTagOverlay);

	// get label by tag
	CCLabelTTF* lbCountDown = (CCLabelTTF*)layer->getChildByTag(kTagOverlayLabel);

	CCString* strp;

	switch(countdown)
	{
	case 3:
		countdown--;

		SimpleAudioEngine::sharedEngine()->playEffect(kMusicFirst);

		strp = CCString::createWithFormat("%d", countdown);

		lbCountDown->setString(strp->getCString());
		break;
	case 2:
		countdown--;

		SimpleAudioEngine::sharedEngine()->playEffect(kMusicFirst);

		strp = CCString::createWithFormat("%d", countdown);

		lbCountDown->setString("1");
		break;
	case 1:
		countdown--;

		SimpleAudioEngine::sharedEngine()->playEffect(kMusicStart);

		lbCountDown->setString("Start");
		break;
	default:
		if(mImpedimentsIsAppear == 0)
		{
			fAddPositionToListImpediments();
			fRandomTimeDisAppear();
			mImpedimentsIsAppear = 1;
			nTimeDisAppear = 0;
			schedule(schedule_selector(HelloWorld::fDisplayImpediments), 1.0f);
		}
		
		removeChildByTag(kTagOverlay);

		unschedule(schedule_selector(HelloWorld::fRemoveOverlay));

		fAddCockroach(5);

		break;
	}
}

void HelloWorld::fAddBackgroundTable()
{
	CCSprite* tableBackground = CCSprite::create(kImageTable);

	tableBackground->setPosition(ccp(mSize.width/2, mSize.height/2));

	CCSize background = tableBackground->boundingBox().size;

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

	tableBackground->setScaleX(visibleSize.width / background.width);

	tableBackground->setScaleY(visibleSize.height / background.height);

	addChild(tableBackground, kZorderBackgroundTable, kTagBackgroundTable);
}

void HelloWorld::fAddLabelScore()
{
	CCString* string = CCString::createWithFormat("%d", score);

	CCLabelTTF* lbScore = CCLabelTTF::create(string->getCString(), kFontName, kFontSize*1.5);

	lbScore->setPosition(ccp(mSize.width/2, mSize.height * 0.97 - 10));

	if(lbScore == NULL)
	{
		return;
	}

	addChild(lbScore, kZorderLabelScore, kTagLabelScore);
}


void HelloWorld::fUpdateUIScore()
{
	CCLabelTTF* lbScore = (CCLabelTTF*) getChildByTag(kTagLabelScore);

	CCString* strp = CCString::createWithFormat("%d", score);

	lbScore->setString(strp->getCString());
}

void HelloWorld::fCreateUIImageLife()
{
	CCSprite* arrCock[kLife];

	CCPoint posTmp;

	for(int i = 0; i < kLife; i++)
	{
		arrCock[i] = CCSprite::create(kImageCockRoach);

		if(i == 0)
		{
			arrCock[i]->setPosition(ccp(mSize.width * 0.95 - kMarginCockroach, mSize.height * 0.97 - kMarginCockroach));

		}
		else
		{
			CCSprite* tmp = (CCSprite*) getChildByTag(kTagImageLife + i - 1);

			posTmp = tmp->getPosition();

			//arrCock[i]->setPosition(ccp(posTmp.x - arrCock[i-1]->boundingBox().size.width/2 - kMarginCockroach, mSize.height * 0.97 - kMarginCockroach));
			arrCock[i]->setPosition(ccp(posTmp.x - arrCock[i-1]->boundingBox().size.width/2 - kMarginCockroach, mSize.height * 0.97 - kMarginCockroach));
		}

		addChild(arrCock[i], kZorderLabelLife, kTagImageLife + i);
	}
}

void HelloWorld::fUpdateUIImageLife(CCLayer* parent)
{
	--life;

	fRmoveImageLife(parent, life);

	fAddCockroach(1);

	if(life == 0)
	{
		fCreatePanelGameOver(this);
	}
}
void HelloWorld::fRmoveImageLife(CCLayer* parent, int index)
{
	parent->removeChildByTag(kTagImageLife + index);
}

void HelloWorld::fCreatePanelGameOver(CCLayer* parent)
{
	fStopAllAction();
	
	showAdsAdmob();

	SimpleAudioEngine::sharedEngine()->playEffect(kMusicEnd);

	isGameOver = 1;

	// Impediment
	CCObject* nObImpediment = NULL;

	CCARRAY_FOREACH(this->listImpediment, nObImpediment)
	{
		StunImpediments * nImpediment = (StunImpediments *)nObImpediment;

		nImpediment->stopAllActions();
	}

	// cockroach
	CCObject* nObCockRoach = NULL;

	CCARRAY_FOREACH(listCockRoach, nObCockRoach)
	{
		CockRoach *nCockRoach = (CockRoach *)nObCockRoach;

		nCockRoach->stopAllActions();

	}

	//panel
	float mSizeWidth = mSize.width;

	float mSizeHeight =  mSize.height;

	CCSprite* flower = CCSprite::create(kImageFlower);

	flower->setScaleX(0.22f);
	CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
	CCSize nSizeScreen = pEGLView->getFrameSize();

	flower->setScaleY(0.22f * ((float)480/nSizeScreen.height * nSizeScreen.width/320));

	flower->setPosition(ccp(mSizeWidth * 0.18, mSizeHeight * 0.9));

	parent->addChild(flower, kZorderBackground);

	// board
	CCSprite* board = CCSprite::create(kImageBoard);

	board->setPosition(ccp(mSizeWidth/2, mSizeHeight * 0.55));

	board->setScale(0.4f);

	addChild(board, kZorderBackground - 1);

	// score
	CCSprite* imgScore = CCSprite::create(kImageScore);

	imgScore->setAnchorPoint(ccp(0, 0.5));

	imgScore->setPosition(ccp(mSizeWidth * 0.2, mSizeHeight * 0.72));

	imgScore->setScale(0.35f);

	addChild(imgScore, kZorderBackground);

	// number score
	CCString* strp = CCString::createWithFormat("%d", score);

	CCLabelTTF* yourScore = CCLabelTTF::create(strp->getCString(), kFontName, kFontSize);

	yourScore->setAnchorPoint(ccp(0, 0.5));

	// position the label yourScore
	yourScore->setPosition(ccp(imgScore->getPositionX() + imgScore->boundingBox().size.width, imgScore->getPositionY()));

	parent->addChild(yourScore, kZorderBackground);

	// top score

	CCSprite* imgTopScore = CCSprite::create(kImageTopScore);

	imgTopScore->setAnchorPoint(ccp(0, 0.5));

	imgTopScore->setPosition(ccp(mSizeWidth * 0.2, mSizeHeight * 0.63));

	//imgTopScore->setScaleX(0.3f);

	imgTopScore->setScale(0.35f);

	addChild(imgTopScore, kZorderBackground);

	// get best score from file
	int topScore = FileOperation::fGetTopScore(kFileTopScore);

	//1CCLOG("diem top %d", topScore);

	if(topScore == -1){

		topScore = score;

	}else
	{
		if( score > topScore) topScore = score;
	}

	FileOperation::fSetTopScore(kFileTopScore, topScore);

	strp = CCString::createWithFormat("%d", topScore);

	CCLabelTTF* bestScore = CCLabelTTF::create(strp->getCString(), kFontName, kFontSize);

	bestScore->setAnchorPoint(ccp(0, 0.5));

	// position the label bestScore
	bestScore->setPosition(ccp(imgTopScore->getPositionX() + imgTopScore->boundingBox().size.width, imgTopScore->getPositionY()));
	
	parent->addChild(bestScore, kZorderBackground);


	CCMenu* menu = CCMenu::create();

	menu->setPosition(ccp(mSizeWidth / 2, 0));

	parent->addChild(menu, kZorderBackground);

	// button play again
	// top score google
	CCMenuItemImage *play = CCMenuItemImage::create(
		"Images/replay.png",
		"Images/replayhover.png",
		this,
		menu_selector(HelloWorld::fResetGame));

	play->setPosition(ccp(0 - 10, mSizeHeight * 0.45));
	play->setScale(0.5f);

	menu->addChild(play);

	// top score google
	CCMenuItemImage *topOnline = CCMenuItemImage::create(
		"Images/topscore.png",
		"Images/topscorehover.png",
		this,
		menu_selector(HelloWorld::topOnline));
	topOnline->setPosition(ccp(0 - 10, mSizeHeight * 0.24));
	topOnline->setScale(0.5f);
	menu->addChild(topOnline, kZorderBackground);
	

	++countGameOver;
	//CCLOG("%d", countGameOver);
	if(countGameOver==5)
	{
		//showMobparten();

		#if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)

				cocos2d::JniMethodInfo methodInfo;
				if (cocos2d::JniHelper::getStaticMethodInfo(methodInfo, "softtech/apps/KillCockroachs/KillCockroachs", "displayFullBanner", "()V"))
				{
					methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
					methodInfo.env->DeleteLocalRef(methodInfo.classID);
				}
		#endif
		countGameOver = 0;
	}

}

void HelloWorld::fAddCockroach(int number)
{
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	// Them gian vao Map

	for(int i=0; i< number; i++)
	{
		float x01 = rand() % (int)mSize.width;

		CCPoint p = ccp( x01 , mSize.height+20);

		CockRoach* cockRoach = new CockRoach(p, 0.25);

		float scalex = cockRoach->boundingBox().size.width / mSize.width;

		float scaley = cockRoach->boundingBox().size.height / mSize.height;

		cockRoach->setScaleX(scalex);

		cockRoach->setScaleY(scaley);

		cockRoach->addComponent(new MoveCockroach());

		listCockRoach->addObject(cockRoach);

		addChild(cockRoach, kZorderCockRoach);
	}
}
//
//bool fIsCollision(CCSprite * sp1, CCPoint * sp2, int minSize)
//{
//	CCRect rectSp1 = sp1->boundingBox();
//	float minX1, minY1, maxX1, maxY1, minX2, minY2, maxX2, maxY2;
//
//	//set tham so object 1
//	minX1 = rectSp1.getMinX();
//	minY1 = rectSp1.getMinY();
//	maxX1 = rectSp1.getMaxX();
//	maxY1 = rectSp1.getMaxY();
//
//	//set tham so object 2
//	minX2 = sp2->x - minSize / 2;
//	minY2 = sp2->y - minSize / 2;
//	maxX2 = sp2->x + minSize / 2;
//	maxY2 = sp2->y + minSize / 2;
//
//	return !(maxX1 < minX2 ||
//		maxX2 < minX1 ||
//		maxY1 < minY2 ||
//		maxY2 < minY1);
//}


bool HelloWorld::fIsCollision(CCSprite * sp1 , CCPoint * sp2 , int minSize)
{
	CCRect rectSp1 = sp1->boundingBox();
	float minX1, minY1, maxX1, maxY1, minX2, minY2, maxX2, maxY2;

	//set tham so object 1
	minX1 = rectSp1.getMinX();
	minY1 = rectSp1.getMinY();
	maxX1 = rectSp1.getMaxX();
	maxY1 = rectSp1.getMaxY();

	//set tham so object 2
	minX2 = sp2->x - minSize/2;
	minY2 = sp2->y - minSize/2;
	maxX2 = sp2->x + minSize/2;
	maxY2 = sp2->y + minSize/2;

	return !(maxX1 < minX2 ||
		maxX2 < minX1 ||
		maxY1 < minY2 ||
		maxY2 < minY1);
}

bool HelloWorld::fIsCollisionWithArmature(CCNode * sp1 , CCPoint * sp2 , int minSize)
{
	
	CCPoint ppp = ccp ( this->convertToWorldSpace(((Impediments *) sp1)->getArmature()->getPosition()).x + this->convertToWorldSpace(((Impediments *) sp1)->getPosition()).x , 
		this->convertToWorldSpace(((Impediments *) sp1)->getArmature()->getPosition()).y + this->convertToWorldSpace(((Impediments *) sp1)->getPosition()).y);
	//((CCArmature*)sp1)->convertToWorldSpace(sp1->getPosition());
	//CCLOG(" **** %f %f", sp2->x , sp2->y);
	//1CCLOG("amatu width height %f %f" , ((Impediments *) sp1)->getArmature()->boundingBox().size.width ,  ((Impediments *) sp1)->getArmature()->boundingBox().size.height);
	//CCLOG("Kiem tra va cham voi Armature 1111111!!  %f %f", ppp.x , ppp.y);
	//1CCLOG("Kiem tra va cham voi Armature !!  %f %f", ((Impediments *) sp1)->getArmature()->getPosition().x , ((Impediments *) sp1)->getArmature()->getPosition().y);
	CCRect rectSp1 = ((Impediments *) sp1)->getArmature()->boundingBox();
	float minX1, minY1, maxX1, maxY1, minX2, minY2, maxX2, maxY2;

	//set tham so object 1
	/*minX1 = rectSp1.getMinX();
	minY1 = rectSp1.getMinY();
	maxX1 = rectSp1.getMaxX();
	maxY1 = rectSp1.getMaxY();*/
	CCRect rect = ((Impediments *) sp1)->getArmature()->boundingBox();
	minX1 = ppp.x - ((Impediments *) sp1)->getArmature()->boundingBox().size.width/2 ;
	minY1 = ppp.y - ((Impediments *) sp1)->getArmature()->boundingBox().size.height/2;
	maxX1 = ppp.x + ((Impediments *) sp1)->getArmature()->boundingBox().size.width/2;
	maxY1 = ppp.y + ((Impediments *) sp1)->getArmature()->boundingBox().size.height/2;

	//1CCLOG("Min X = %f Max X = %f Min Y = %f Max Y = %f",minX1,maxX1,minY1,maxY1);
	//set tham so object 2
	minX2 = sp2->x - minSize/2 + 2;
	minY2 = sp2->y - minSize/2 + 2;
	maxX2 = sp2->x + minSize/2 - 2;
	maxY2 = sp2->y + minSize/2 - 2;

	 int a1 = !(maxX1 < minX2 ||
		maxX2 < minX1 ||
		maxY1 < minY2 ||
		maxY2 < minY1);
	 if(a1){
		 //CCLOG("CHAM TRUNG CMNR");
	 }else{
		 //CCLOG("XIT");
	 }
	 return a1;
}


CCLabelTTF* HelloWorld::fAddLabelLife(CCPoint pos, char* fontName, int fontSize, int life)
{
	CCLabelTTF* lbLife;

	CCString* string = CCString::createWithFormat("%d", life);

	lbLife = CCLabelTTF::create(string->getCString(), fontName, fontSize);

	lbLife->setPosition(ccp(pos.x, pos.y));

	if(lbLife == NULL)
	{
		return NULL;
	}

	return lbLife;
}

void HelloWorld::fAddLabelLife(CCLayer* parent, CCPoint pos, char* fontName, int fontSize, int life)
{
	CCLabelTTF* lbLife = fAddLabelLife(pos, fontName, fontSize, life);

	if(lbLife == NULL)
	{
		return;
	}

	parent->addChild(lbLife, kZorderLabelLife, kTagLabelLife);
}

void HelloWorld::fUpdateUILife(CCLabelTTF* lbLife, int life)
{
	if(lbLife == NULL) return;

	CCString* strp = CCString::createWithFormat("%d", life);

	lbLife->setString(strp->getCString());
}


CCLabelTTF* HelloWorld::fAddLabelScore(CCPoint pos, char* fontName, int fontSize, int score)
{
	CCString* string = CCString::createWithFormat("%d", score);

	CCLabelTTF* lbScore = CCLabelTTF::create(string->getCString(), fontName, fontSize);

	lbScore->setPosition(ccp(pos.x, pos.y));

	if(lbScore == NULL)
	{
		return NULL;
	}

	return lbScore;
}

void HelloWorld::fAddLabelScore(CCLayer* parent, CCPoint pos, char* fontName, int fontSize, int score)
{
	CCLabelTTF* lbScore = fAddLabelScore(pos, fontName, fontSize, score);

	if(lbScore == NULL){
		return;
	}

	parent->addChild(lbScore, kZorderLabelScore, kTagLabelScore);
}

void HelloWorld::fUpdateUIScore(CCLabelTTF* lbScore, int score)
{
	if(lbScore == NULL) return;

	CCString* strp = CCString::createWithFormat("%d", score);

	lbScore->setString(strp->getCString());
}




void HelloWorld::fAddImpediments(CCPoint point){
	mImpediment = new StunImpediments(1);
	mImpediment->setPosition(point);
	mImpediment->fSetAppear(0);
	this->addChild(mImpediment, kZoderImpediment);
}

void HelloWorld::fAddListImpediments()
{
	//size la kick thuoc man hinh

	/*mStunImpediment = new StunImpediments(1);
	mStunImpediment->setPosition(ccp(300,300));
	mStunImpediment->setVisible(false);
	mStunImpediment->fSetAppear(0);
	this->addChild(mStunImpediment, kZoderImpediment);*/

	mImpedimentsIsAppear = 0;
	listImpediment = CCArray::createWithCapacity(4);
	listImpediment->retain();
	for(int i = 0; i< 4 ;i++)
	{
		StunImpediments *nStunImpediment = new StunImpediments(i%4);
		nStunImpediment->fSetPosition(ccp(-100, -100));
		nStunImpediment->fSetAppear(0);
		nStunImpediment->setVisible(false);
		this->listImpediment->addObject(nStunImpediment);
		this->addChild(nStunImpediment, kZoderImpediment);
	}
}

void HelloWorld::fVibrateAndBroken(StunImpediments* impediment)
{
	impediment->fSetBroken(1);
	impediment->fRunEffectsBroken();
	this->runAction(impediment->fEffectsVibrate(0.5));

}

void HelloWorld::fShockAndBroken(StunImpediments* impediment)
{
	impediment->fSetBroken(1);
	impediment->fRunEffectsBroken();
	//this->runAction(impediment->fEffectsShock(2));
	mIsDie = 1;
	nTimeDie = 150;
}

void HelloWorld::fBaseScreen()
{
	if ( this->numberOfRunningActions() == 0 && this->getGrid() != NULL)
		this->setGrid(NULL);
}

int* HelloWorld::fRandomPosition()
{
	int* arrRandom = new int[kImpedimentArrayAppearWidth*kImpedimentArrayAppearHeight];
	srand(time(0)*100);
	for(int i=0; i < kImpedimentArrayAppearHeight ; i++)
	{
		arrRandom[(rand() % kImpedimentArrayAppearWidth)+ i*kImpedimentArrayAppearHeight] = 1;
	}
	return arrRandom;
}

void HelloWorld::fAddPositionToListImpediments()
{
	int nLocationRandom;
	int* arrRandom = fRandomPosition();
	float nNumberGridHeight = mSize.height / (kImpedimentArrayAppearHeight+1);
	float nNumberGridWidth = mSize.width / (kImpedimentArrayAppearWidth+1);


	int i = 0;
	CCObject* nObImpediment = NULL;
	CCARRAY_FOREACH(this->listImpediment, nObImpediment)
	{
		StunImpediments* nImpediment = (StunImpediments*)nObImpediment;
		for(int j = i*4; j < (i+1)*4; j++)
		{
			if(arrRandom[j] == 1)
				nLocationRandom = j%4;
		}
		
		nImpediment->fSetPosition(ccp(nNumberGridWidth/2 + nNumberGridWidth/2 + (float)nLocationRandom*nNumberGridWidth, 
			nNumberGridHeight + (float)i*nNumberGridHeight));

		//CCLOG("%f-%f -",nNumberGridWidth, nNumberGridHeight/2 + (float)i*nNumberGridHeight);
		i++;
	}

}

void HelloWorld::fRandomTimeDisAppear()
{
	bool test;
	int* listRandom = new int[kImpedimentArrayAppearHeight];
	int r;
	for(int i = 0; i < kImpedimentArrayAppearHeight; i++)
	{
		do
		{
			r = rand() % kImpedimentArrayAppearHeight;
			test = false;
			for(int j=0;j<i;j++)
			{
				if(listRandom[j] == r)
				{
					test = true;
					break;
				}
			}
		}while(test);
		listRandom[i] = r;
	}
	int k =0;
	CCObject* nObImpediment = NULL;
	CCARRAY_FOREACH(this->listImpediment, nObImpediment)
	{
		StunImpediments* nImpediment = (StunImpediments*)nObImpediment;
		nImpediment->fSetTimeDisAppearBeforeAppear(rand()%10 + listRandom[k]*10);
		k++;
	}
}

void HelloWorld::fDisplayImpediments(float delta)
{
	CCObject* nObImpediment = NULL;
	CCARRAY_FOREACH(this->listImpediment, nObImpediment)
	{
		StunImpediments* nImpediment = (StunImpediments*)nObImpediment;
		if(nImpediment->fGetTimeDisAppearBeforeAppear() == nTimeDisAppear)
		{
			nImpediment->setVisible(true);
			nImpediment->fRunEffectsAppear(kImpedimentsTimeAppear, kImpedimentsNumber);
		}
		////1CCLOG("%d",nImpediment->fGetTimeDisAppearBeforeAppear());
	}
	nTimeDisAppear++;
}

void HelloWorld::fStopAllAction()
{
	CCObject* nObImpediment = NULL;

	CCARRAY_FOREACH(this->listImpediment, nObImpediment)
	{
		StunImpediments * nImpediment = (StunImpediments *)nObImpediment;
		nImpediment->fSetTimeDisAppearBeforeAppear(-100);
		nImpediment->stopAllActions();
	}

	// cockroach
	CCObject* nObCockRoach = NULL;

	CCARRAY_FOREACH(listCockRoach, nObCockRoach)
	{
		CockRoach *nCockRoach = (CockRoach *)nObCockRoach;

		nCockRoach->stopAllActions();

	}
}


//----------------------------
bool HelloWorld::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
	if(isGameOver)
		return false;
	CCPoint touchLocation = this->convertTouchToNodeSpace(touch);
	CCObject* nObImpediment = NULL;
	CCObject* nObCockRoach = NULL;

	int choinhac = 0;

	CCARRAY_FOREACH(listCockRoach, nObCockRoach)
	{
		CockRoach *nCockRoach = (CockRoach *)nObCockRoach;

		if (nCockRoach->getStatus() == IDLE)
		{
			nCockRoach->setStatus(RUN);
		}


		if (fIsCollision(nCockRoach, &touchLocation, 9) == 1)
		{
			//1CCLOG("Kiem tra va cham --> Cham trung cmnr");

			choinhac = 1;

			score++;
			
			nCockRoach->fUpdateDieImage();

			//update score 
			fUpdateUIScore();

			listCockRoach->removeObject(nCockRoach, true);

			////1CCLOG("chia du : %d", score % 2);
		}
	}

	if (choinhac)
	{
		SimpleAudioEngine::sharedEngine()->playEffect(kMusicHit);
		fAddCockroach(1);
		if (score != 0 && score % 4 == 0){
			fAddCockroach(1);
		}

	}

	CCARRAY_FOREACH(this->listImpediment, nObImpediment)
	{
		StunImpediments * nImpediment = (StunImpediments *)nObImpediment;
		//nImpediment->getAnimation()->playByIndex(0);
		//1CCLOG("%f", nImpediment->boundingBox().size.width);
		if (nImpediment->fGetAppear() != kImpedimentDisappear){

			if (fIsCollisionWithArmature(nImpediment, &touchLocation, 10) == 1)
			{
				if (nImpediment->fGetBroken() == kImpedimentNotBroken && nImpediment->fGetAppear() == 1)
				{

					SimpleAudioEngine::sharedEngine()->playEffect(kMusicBroken);

					fVibrateAndBroken(nImpediment);

					mIsDie = 1;

					nTimeDie = 50;

					fStopAllAction();

				}
				else if (nImpediment->fIsBrokenAndDisAppear() == kImpedimentNotBrokenAndAppear)
				{
					//1CCLOG("be roi danh chi nua cha");
					//this->runAction(impediment->fEffectsShock(2));


					//fImpedimentPuffBlood();
				}
			}
		}
	}

	return true;
}

void HelloWorld::onEnter()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
	CCLayer::onEnter();
}

void HelloWorld::onExit()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCLayer::onExit();
}


void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
	CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	exit(0);
#endif
#endif
}

void HelloWorld::showAdsAdmob()
{
	#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //Android
	cocos2d::JniMethodInfo methodInfo;

    if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, "softtech/apps/KillCockroachs/KillCockroachs", "showAdmobJNI", "()V")) {
        return;
    }

    methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
    methodInfo.env->DeleteLocalRef(methodInfo.classID);
	#endif
	
}

void HelloWorld::hideAdsAdmob()
{
	#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //Android
	cocos2d::JniMethodInfo methodInfo;

    if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, "softtech/apps/KillCockroachs/KillCockroachs", "hideAdmobJNI", "()V")) {
        return;
    }

    methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
    methodInfo.env->DeleteLocalRef(methodInfo.classID);
	#endif
	
}

void HelloWorld::showMobparten()
{
	#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //Android
	cocos2d::JniMethodInfo methodInfo;

    if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, "softtech/apps/KillCockroachs/KillCockroachs", "showModparten", "()V")) {
        return;
    }

    methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
    methodInfo.env->DeleteLocalRef(methodInfo.classID);
	#endif
	
}


void HelloWorld::topOnline(CCObject* sender){
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //Android
	cocos2d::JniMethodInfo methodInfo;

	if (!cocos2d::JniHelper::getStaticMethodInfo(methodInfo, "softtech/apps/KillCockroachs/KillCockroachs", "showHeaderBoard", "()V")) {
		return;
	}

	methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
	methodInfo.env->DeleteLocalRef(methodInfo.classID);
#endif

}